package it.uniba.di.collab.jazzfeed.service;

import it.uniba.di.collab.jazzfeed.common.IJazzFeedService;
import it.uniba.di.collab.jazzfeed.common.model.JazzfeedPackage;
import it.uniba.di.collab.jazzfeed.common.model.User;
import it.uniba.di.collab.jazzfeed.common.model.query.BaseUserQueryModel;
import it.uniba.di.collab.jazzfeed.common.model.query.BaseUserQueryModel.UserQueryModel;

import java.util.ArrayList;

import com.ibm.team.repository.common.IItem;
import com.ibm.team.repository.common.IItemType;
import com.ibm.team.repository.common.TeamRepositoryException;
import com.ibm.team.repository.common.query.IItemQuery;
import com.ibm.team.repository.common.query.IItemQueryPage;
import com.ibm.team.repository.common.service.IQueryService;
import com.ibm.team.repository.service.AbstractService;
import com.ibm.team.repository.service.IRepositoryItemService;
import com.friendfeed.api.*;
public class JazzFeedService extends AbstractService implements IJazzFeedService {

   static IItemType getUserItemType() {
      return IItemType.IRegistry.INSTANCE
      .getItemType(JazzfeedPackage.eINSTANCE.getUser().getName(), JazzfeedPackage.eNS_URI);
   }

   public User[] getUser() throws TeamRepositoryException {
		IQueryService queryService = getService(IQueryService.class);

		UserQueryModel queryModel = BaseUserQueryModel.UserQueryModel.ROOT;
		IItemQuery itemQuery = IItemQuery.FACTORY.newInstance(queryModel);

		IItemQueryPage itemQueryPage = queryService.queryItems(itemQuery,
				IQueryService.EMPTY_PARAMETERS,
				IQueryService.ITEM_QUERY_MAX_PAGE_SIZE);

		IRepositoryItemService repositoryItemService = getService(IRepositoryItemService.class);
		IItem[] items = repositoryItemService.fetchItems(itemQueryPage
				.handlesAsArray(), null);
		ArrayList<User> usr = new ArrayList<User>();
		for (IItem item : items) {
			if (item instanceof User) {
				usr.add((User) item);
			}
		}

		return (User[]) usr.toArray(new User[usr.size()]);

	}
   
   
   public User postUser(NewUserParameters params)
         throws TeamRepositoryException {
      IRepositoryItemService repositoryItemService = getService(IRepositoryItemService.class);
       User usr = (User) getUserItemType().createItem();
       usr.setLogin(params.text);
     usr = (User) repositoryItemService.saveItem(usr);
      return usr;
   }

public void postToRoom(String message) throws TeamRepositoryException {
	FriendFeedService friendfeed = new FriendFeedServiceImpl(); //TODO: ha bisogno di username e password come argomenti da prendere da USER
	friendfeed.publishLink("",message);
	
}
   
}
